#include <stdio.h>
#include "expat.h"

/*
 * 演示Expat的使用方式
 * 从标准输入读取XML流, 解析后输出解析的详细内容
 * expatparser < test.data
 */

char *substr(const char *s, int n1, int n2) {
  char *sp = malloc(sizeof(char)*(n2-n1+2));
  int i, j = 0;
  for (i=n1; i<=n2; i++) {
   sp[j++]=s[i];
  }
  sp[j]=0;
  return sp;
}


/*
APIs:
<1> XML_ParserCreate
    Create a new parser object.
<2> XML_SetElementHandler
    Set handlers for start and end tags.
<3> XML_SetCharacterDataHandler
    Set handler for text.
<4> XML_Parse
    Pass a buffer full of document to the parser 
*/

#define BUFFSIZE 1024
char buf[BUFFSIZE];

void startElement(void *data, const char *name, const char **attr) {
  int i;

  // dep & name
  int *dep = (int *)data;
  printf("dep - %d, %s", *dep, name);
  *dep += 1;

  // attributes
  for(i = 0; attr[i]; i += 2) {
    printf(" %s='%s'", attr[i], attr[i + 1]); 
  }
  printf("\n");
}

void endElement(void *data, const char *name) {
  int *dep = (int *)data;
  *dep -= 1;
}

void dataElement(void *data, const char *s, int len) {
  char *text = substr(s, 0, len-1);
  printf("text - %s\n", text);
  free(text);
}


int main(int argc, char *argv[]) {
  int dep = 0;
  XML_Parser parser = XML_ParserCreate(NULL); // 或者"UTF-8"
  XML_SetElementHandler(parser, startElement, endElement);
  XML_SetCharacterDataHandler(parser, dataElement);
  XML_SetUserData(parser, &dep);

  for(;;) {
    int done, len;
    // 从一个流中读数据
    // int fread(void *ptr, int size, int nitems, FILE *stream);
    // size: 单个元素的大小(size), 单位是byte而不是bit
    // nitems: 元素个数
    len = fread(buf, 1, BUFFSIZE, stdin);
    done = feof(stdin);
    
    if(!XML_Parse(parser, buf, len, done)) {
      return -1;
    }

    if(done) {
      break;
    }
  }
  return 0;
}

